package com.taofucai.backend.Tools;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.List;

public class TokenUtils {
    private static final String SECRET_KEY = "eyJqdGkiOiI2MTE4OTNlYzVmYWQ0NmJhODgzM2Y2NmYwYmM0MjZmMCIsInN1YiI6In"; // 自定义密钥
    private static final long EXPIRATION_TIME = 86400000; // 过期时间为24小时

    // 生成只有一个参数的Token
    public static String generateToken(String subject) {
        return Jwts.builder()
                .setSubject(subject)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 有效期为24小时
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    // 生成两个参数的Token
    public static String generateToken(String subject, String issuer) {
        return Jwts.builder()
                .setSubject(subject)
                .setIssuer(issuer)
                .setIssuedAt(new Date())
                // .setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 有效期为24小时
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    // 生成包含列表参数的Token
    public static <T> String generateToken(String subject, List<T> roles ,List<T> perminssions) {
        return Jwts.builder()
                .setSubject(subject)
                .claim("roles", roles)
                .claim("permissions",perminssions)
                .setIssuedAt(new Date())
                // .setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 有效期为24小时
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    // 生成没有过期时间的Token
    public static String generateTokenWithoutExpiration(String subject) {
        return Jwts.builder()
                .setSubject(subject)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    public static String generateExpiredToken() {
        Date now = new Date();
        Date expirationDate = new Date(now.getTime() + EXPIRATION_TIME);

        return Jwts.builder()
                .setIssuedAt(now)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS256, "SECRET_KEY")
                .compact();
    }

    // 解析Token
    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();
    }
}
